home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2825 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  1.6 KB

  1. Path: inet.dp.beckman.com!newsmaster
  2. Newsgroups: comp.lang.c++
  3. Subject: Re: Q: Returning a reference
  4. Message-ID: <4dp1a7$bo8@phoenix.dse.beckman.com>
  5. From: jawalker@ccgate.dp.beckman.com (Jack Walker)
  6. Date: Fri, 19 Jan 1996 21:55:48 GMT
  7. References: <4cvsm2$5ig@dub-news-svc-4.compuserve.com>
  8.  <30FA95E1.50C@public.sta.net.cn>
  9. Distribution: world
  10. Organization: DDC, Beckman Instruments, Inc.
  11. NNTP-Posting-Host: j_walker.dse.beckman.com
  12.  
  13. Xu Ji <jafd@public.sta.net.cn> wrote:
  14.  
  15. >Martin Aupperle wrote:
  16. >: 
  17. >: Borland C++ V4.5 does not allow to return a reference to a local
  18. >: variable:
  19. >: 
  20. >: int &doIt() {
  21. >: 
  22. >:   int i = 7;
  23. >:   return i;  // syntax error
  24. >:   }
  25. >: 
  26. >: I remember that I once had a compiler that did allow it (it gave me
  27. >: only a warning).
  28. >: Which one is right? I think that it should be an error because after
  29. >: the function has terminated, the reference has no data object it is
  30. >: bound to any more.
  31. >: 
  32. >: Martin
  33. >: 
  34. >: -----------------------------------
  35. >: Signatures are a waste of bandwidth
  36. >: -----------------------------------
  37.  
  38. >I think it should be an error, and I test it under Borland C++
  39. >and Watcom C++, both this two compiler report it as an error.
  40.  
  41. >but the following function can be compiled:
  42.  
  43. > int &doIt()
  44. > {
  45. >     int i = 7;
  46. >     return (int &)i;
  47. > }
  48.  
  49. >Best wishs,
  50. >Xu yifeng
  51.  
  52. Do you really want to return a reference to an object that is
  53. allocated on the stack?  After doIt returns the space that i occupied
  54. is available to be overwritten when the next stack frame is created.
  55.  
  56.  
  57. Work:jawalker@ccgate.dp.beckman.com
  58. Home:75341.3260@compuserve.com
  59.  
  60.